// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://wx.qq.com/
// @grant        none
// ==/UserScript==

/* ajax全局拦截方法注册 */
!function(t){function r(i){if(n[i])return n[i].exports;var o=n[i]={exports:{},id:i,loaded:!1};return t[i].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}var n={};return r.m=t,r.c=n,r.p="",r(0)}([function(t,r){!function(t){t.hookAjax=function(t){function r(t){return function(){return this.hasOwnProperty(t+"_")?this[t+"_"]:this.xhr[t]}}function n(r){return function(n){var i=this.xhr,o=this;return 0!=r.indexOf("on")?void(this[r+"_"]=n):void(t[r]?i[r]=function(){t[r](o)||n.apply(i,arguments)}:i[r]=n)}}function i(r){return function(){var n=[].slice.call(arguments);if(!t[r]||!t[r].call(this,n,this.xhr))return this.xhr[r].apply(this.xhr,n)}}return window._ahrealxhr=window._ahrealxhr||XMLHttpRequest,XMLHttpRequest=function(){this.xhr=new window._ahrealxhr;for(var t in this.xhr){var o="";try{o=typeof this.xhr[t]}catch(t){}"function"===o?this[t]=i(t):Object.defineProperty(this,t,{get:r(t),set:n(t)})}},window._ahrealxhr},t.unHookAjax=function(){window._ahrealxhr&&(XMLHttpRequest=window._ahrealxhr),window._ahrealxhr=void 0}}(window)}]);

/*
 * 由于网页微信信息展示的局限性，有以下2点需要注意：
 * 1、抓取信息的微信账号，不参与发送信息，只能接受信息
 * 2、抓取信息时，聊天对话框一定要是当前聊天群组，否则一些信息无法抓取
 */
(function() {
    const serverUrl = 'https://wdn.com:8443';
	Date.prototype.format = function(format) {
		var o = {
			'M+': this.getMonth() + 1,
			'd+': this.getDate(),
			'h+': this.getHours(),
			'H+': this.getHours(),
			'm+': this.getMinutes(),
			's+': this.getSeconds(),
			'q+': Math.floor((this.getMonth() + 3) / 3),
			'S': this.getMilliseconds()
		};
		if(/(y+)/.test(format)) {
			format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
		}
		for(var k in o) {
			if(new RegExp('(' + k + ')').test(format)) {
				format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
			}
		}
		return format;
	};

	function convertImgToBase64(url, callback, outputFormat) {
		var canvas = document.createElement('CANVAS'),
			ctx = canvas.getContext('2d'),
			img = new Image();
		img.crossOrigin = 'Anonymous';
		img.onload = function() {
			canvas.height = img.height;
			canvas.width = img.width;
			ctx.drawImage(img, 0, 0);
			var dataURL = canvas.toDataURL(outputFormat || 'image/png');
			callback.call(this, dataURL);
			canvas = null;
		};
		img.src = url;
	}

	function dataURItoBlob(dataURI) {
		var byteString = atob(dataURI.split(',')[1]);
		var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
		var ab = new ArrayBuffer(byteString.length);
		var ia = new Uint8Array(ab);
		for(var i = 0; i < byteString.length; i++) {
			ia[i] = byteString.charCodeAt(i);
		}
		return new Blob([ab], {
			type: mimeString
		});
	}

    //判断属性是否为空
    function isEmpty(obj) {
        for (var name in obj) {
            return false;
        }
        return true;
    }

    //初始化好友或群的映射关系
    var chatUserList={};
    function getChatUserList() {
        var elDom = $('#J_NavChatScrollBody .chat_item');
        for(var i=0; i<elDom.length; i++) {
            var el = elDom[i];
            var userName = $(el).data('username');
            var nickName = $(el).find('.nickname_text').text();
            chatUserList[userName] = nickName;
        }
        
        if(isEmpty(chatUserList)) {
            setTimeout(function() {
                getChatUserList();
            }, 1000);
        }
    }
    getChatUserList();
    
    var receiverArrary = ["新光扯淡群","爱如花-订单群"];    //定义可以抓取的群
    var receivedMsgList = {};
    
    function getUserMsg() {
        if(isEmpty(chatUserList)) return;
        for(var key in receivedMsgList) {
            var msgJson = receivedMsgList[key];
            var msgBody = {};
            
            //Object.keys(chatUserList).map(key => {console.log(key + "======>" + chatUserList[key]);});
            //当第三者发消息到群里时，FromUserName才是群的代号；
            if($.inArray(chatUserList[msgJson.FromUserName], receiverArrary) == -1) {
                delete receivedMsgList[msgJson.MsgId];
                console.log('不是要抓取的群：' + isEmpty(receivedMsgList));
                continue;
            }
            //接收群
            msgBody.toUserName = chatUserList[msgJson.FromUserName];
            //消息ID
            msgBody.messageId = msgJson.MsgId;
            //消息类型、消息内容
            if (msgJson.MsgType == 1) {
                msgBody.messageType = 'text';
                msgBody.messageContent = msgJson.Content.split(':<br/>')[1];
            } else if(msgJson.MsgType == 3) {
                msgBody.messageType = 'picture';
                msgBody.messageContent = $('.js_message_bubble[data-cm$=' + msgJson.MsgId + '\\"\\}]').find('.msg-img').attr('src');
            } else {
                delete receivedMsgList[msgJson.MsgId];
                console.log('消息类型不对：' + isEmpty(receivedMsgList));
                return;
            }
            //发送人
            msgBody.fromUserName = $('.js_message_bubble[data-cm$=' + msgJson.MsgId + '\\"\\}]').prev().text();
            //此微信号所属人
            msgBody.loginNick = $('.display_name').text();
            //消息发送时间
            msgBody.messageTime = msgJson.CreateTime && new Date(msgJson.CreateTime * 1000).format('yyyy-MM-dd hh:mm:ss');
            
            //console.log(msgBody);
            //delete receivedMsgList[msgJson.MsgId];
            //return;
            
            $.ajax({
                url: serverUrl + '/haierp1/wx/uploadMessage',
                method: 'POST',
                async : false,    //同步
                data: msgBody,
                success: function() {
                    if (msgBody.messageType === 'picture') {
                        convertImgToBase64(msgBody.messageContent.replace('&type=slave', ''), function(base64Img) {
                            var form = new FormData();
                            form.append('pic', dataURItoBlob(base64Img));
                            //console.log('prepare to upload img');
                            $.ajax({
                                url: serverUrl + '/haierp1/uploadFile/picUpload',
                                method: 'POST',
                                data: form,
                                processData: false,  // 告诉jQuery不要去处理发送的数据
                                contentType: false,
                                success: function(res) {
                                    var data = JSON.parse(res);
                                    $.ajax(serverUrl + '/haierp1/wx/uploadMessImage?messageId=' + msgBody.messageId + '&imageUrl=' + data.data);
                                    delete receivedMsgList[msgBody.messageId];
                                    //console.log(receivedMsgList);
                                }
                            });
                        });
                    } else {
                        delete receivedMsgList[msgBody.messageId];
                        //console.log(receivedMsgList);
                    }
                },
                error: function() {
                    //console.log(receivedMsgList);
                }
            });
            
        }
    }
    
    // 1. 拦截ajax请求，获取消息JSON
	hookAjax({
		onreadystatechange: function(xhr) {
			var data = xhr.responseText;  //ajax请求结果
			var resUrl = xhr.responseURL; //ajax请求路径
			if(resUrl.match('webwxsync') && xhr.readyState===4 && xhr.status===200 && data) {
                try {data = JSON.parse(data);} catch(err) {return;}
                if(data.AddMsgList && data.AddMsgList.length>0) {
                    console.log('** COLLECTOR ** 获取了消息');
                    //console.log(data.AddMsgList);
                    data.AddMsgList.forEach(function(msg) {
                        var msgId = msg.MsgId;
                        if(!receivedMsgList[msgId]) receivedMsgList[msgId] = msg;
                    });
                    setTimeout(getUserMsg, 600);
                }
			}
		}
	});
})();